let _debounceTimeout = null,
	_throttleRunning = false


/**
 * 防抖  --延迟执行函数
 * @param {Function} 执行函数
 * @param {Number} delay 延时 ms
 */
const debounce = (fn, delay = 500) => {
	clearTimeout(_debounceTimeout);
	_debounceTimeout = setTimeout(() => {
		fn();
	}, delay)
}

/**
 * 节流  --添加执行间隔
 * @param {Function} 执行函数 
 * @param {Number} delay 延时ms
 */
const throttle = (fn, delay = 500) => {
	if (_throttleRunning) {
		return;
	}
	_throttleRunning = true;
	fn();
	setTimeout(() => {
		_throttleRunning = false;
	}, delay);
}

/** 
 * toast
 * @param {type}  
 */
const toast = (title = '', param = {}) => {
	if (!title) return;
	uni.showToast({
		title,
		duration: param.duration || 1500,
		mask: param.mask || false,
		icon: param.icon || 'none'
	});
}

function requestOpenBluetooth() {
	var main, BluetoothAdpter, BAdapter;
	switch (uni.getSystemInfoSync().platform) {
		case 'android':
			console.log('android');
			main = plus.android.runtimeMainActivity();
			BluetoothAdpter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
			BAdapter = BluetoothAdpter.getDefaultAdapter();
			if (!BAdapter.isEnabled()) BAdapter.enable();
			break;
		case 'ios':
			break;
		default:
			break;
	}
}

function getAge(birthday) {
	let birth = new Date(birthday);
	let now = new Date();
	let age = now.getFullYear() - birth.getFullYear();
	let m = now.getMonth() - birth.getMonth();
	if (m < 0 || (m === 0 && now.getDate() < birth.getDate())) {
		age--;
	}
	return age;
}

function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}

function isNull(obj) {
	if (obj == [] || obj == undefined || obj == null || obj == "") {
		return true;
	};
	return false;
}
//crc16算法
function crc16_false(buffer) {
	var crc = 0xffff;
	let polynomial = 0x1021;
	for (var index = 0; index < buffer.length; index++) {
		var b = buffer[index];
		for (var i = 0; i < 8; i++) {
			let bit = ((b >> (7 - i) & 1) == 1);
			let c15 = ((crc >> 15 & 1) == 1);
			crc <<= 1;
			if (c15 ^ bit)
				crc ^= polynomial;
		}
	}
	var hi = ((crc & 0xFF00) >> 8); //高位置
	var lo = (crc & 0x00FF); //低位置
	return [hi, lo];
}

//计算当前日期
function Current_date() {
	const time = new Date()
	const y = time.getFullYear() // 可返回一个表示年份的 4 位数字
	const m = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1  // 可返回表示月份的数字。返回值是 0（一月） 到 11（十二月） 之间的一个整数 // 注意： 一月为 0, 二月为 1, 以此类推。
	const d = time.getDate() < 10 ? '0' + time.getDate() : time.getDate()
	return y + '-' + m + '-' + d
}

function getDateYYYYMMddHHMMSS() {
	const date = new Date();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const strDate = date.getDate().toString().padStart(2, '0');
	const starHours = date.getHours().toString().padStart(2, '0');
	const starMinutes = date.getMinutes().toString().padStart(2, '0');
	const starSeconds = date.getSeconds().toString().padStart(2, '0');
	let format = `${date.getFullYear()}-${month}-${strDate} ${starHours}:${starMinutes}:${starSeconds}`;
	return format
}

//时间格式化输出
function date_format(micro_second) {
	//秒数
	var second = Math.floor(micro_second / 1000);
	// 时  位
	var hr = Math.floor(second / 3600);
	// 分钟位
	var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
	// 秒位
	var sec = fill_zero_prefix((second - hr * 3600 - min * 60)); // equal to => var sec = second % 60;
	// 毫秒位，保留2位
	var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
	return min + ":" + sec;
}

// 补足位数 00：00
function fill_zero_prefix(num) {
	return num < 10 ? "0" + num : num;
}

function toDouble(num) {
	if (num < 10) {
		return '0' + num;
	} else {
		return '' + num;
	}
}

// 将日期格式转换成 年 - 月 -日 形式
function Turn_Date(date) {
	var Date1 = new Date(date);
	var turnDate = Date1.getFullYear() + '-' + Number(Date1.getMonth() + 1) + '-' + Date1.getDate();
	return turnDate;
}

///解密算法
function Data_Decrypt(s, len) {
	var key = [5, 4, 3, 1, 2, 7, 6, 0];
	let i;
	let j;
	let temp;
	let temp1 = new Array();
	for (i = 0; i < parseInt(len / 8); i++) {
		temp1[i * 8 + key[0]] = s[i * 8];
		temp1[i * 8 + key[1]] = s[i * 8 + 1];
		temp1[i * 8 + key[2]] = s[i * 8 + 2];
		temp1[i * 8 + key[3]] = s[i * 8 + 3];
		temp1[i * 8 + key[4]] = s[i * 8 + 4];
		temp1[i * 8 + key[5]] = s[i * 8 + 5];
		temp1[i * 8 + key[6]] = s[i * 8 + 6];
		temp1[i * 8 + key[7]] = s[i * 8 + 7];
	}
	for (j = i * 8; j < len; j++) {
		temp1[j] = s[j];
	}
	for (j = 0; j < len; j++) {
		temp = 0;
		temp |= (0x01 & temp1[j]) << key[0];
		temp |= ((0x02 & temp1[j]) >> 1) << key[1];
		temp |= ((0x04 & temp1[j]) >> 2) << key[2];
		temp |= ((0x08 & temp1[j]) >> 3) << key[3];
		temp |= ((0x10 & temp1[j]) >> 4) << key[4];
		temp |= ((0x20 & temp1[j]) >> 5) << key[5];
		temp |= ((0x40 & temp1[j]) >> 6) << key[6];
		temp |= ((0x80 & temp1[j]) >> 7) << key[7];
		s[j] = temp;
	}
	return s;
}

// 生成指定范围内的随机数
function random(m, n) {
	var num = Math.floor(Math.random() * (m - n) + n);
	return num;
}

//byte to float 
function convertFloat(byteStr) {
	let arrayBuffer = new Uint8Array(byteStr).buffer;
	var dataView = new DataView(arrayBuffer);
	return dataView.getFloat32(0);
}

// 隐藏手机号码
function HideTel(tel) {
	var reg = /^(\d{3})\d{4}(\d{4})$/;
	return tel.replace(reg, "$1****$2");
}
// 找到html中的src   var reg1 = /src=\"(.+?)\"/g;
function getImgSrc(str) {
	var reg = /src=\"(.+?)\"/g;
	var list = [];
	var result = null;
	do {
		result = reg.exec(str);
		result && list.push(result[1]);
	} while (result);
	if (list.length > 9) {
		list = list.slice(0, 9);
	}
	return list;
}
// 天数计算器
function Dayz(startDate) {
	var sdate = new Date(startDate.replace(/-/g, "/"));
	var now = new Date();
	var days = now.getTime() - sdate.getTime();
	var day = parseInt(days / (1000 * 60 * 60 * 24));
	return day;
};

// 版本对比
function compareVersion(version1, version2) {
	let v1 = version1.split('.');
	let v2 = version2.split('.');
	let len = Math.max(v1.length, v2.length);
	if (v1.length < len) {
		v1.push('0');
	}
	if (v2.length < len) {
		v2.push('0');
	}
	for (let i = 0; i < len; i++) {
		let num1 = parseInt(v1[i]);
		let num2 = parseInt(v2[i]);
		if (num1 > num2) {
			return 1;
		} else if (num1 < num2) {
			return -1;
		}
	}
	return 0;
}

function hexToString(str) {
	var val = "",
		len = str.length / 2;
	for (var i = 0; i < len; i++) {
		val += String.fromCharCode(parseInt(str.substr(i * 2, 2), 16));
	}
	return val
}

function getCurrentMonthTime(_date) {
	const date = new Date(_date);
	// 设置为日期1号
	date.setDate(1);
	// 获取当前月份(date.getMonth()返回的是0-11)
	let month = parseInt(date.getMonth() + 1);
	// 获取当月第一天日期
	let startDay = date.getDate();
	// 获取当前月的最后一天。参数0代表上个月的最后一天
	const endOfMonth = new Date(date.getFullYear(), month, 0).getDate();
	// 设置日期为当前月的最后一天
	date.setDate(endOfMonth);
	// 获取当月最后一天日期
	let endDay = date.getDate();
	if (month < 10) month = '0' + month
	if (startDay < 10) startDay = '0' + startDay
	if (endDay < 10) endDay = '0' + endDay
	const startTime = date.getFullYear() + '-' + month + '-' + startDay + " " + "00:00:00";
	const endTime = date.getFullYear() + '-' + month + '-' + endDay + " " + "23:59:59";
	return [startTime, endTime]
}
//大端模式 bytes --> number
function BytesToIntBigEndian(bytes) {
	var val = 0;
	for (var i = 0; i < bytes.length; ++i) {
		val += bytes[i];
		if (i < bytes.length - 1) {
			val = val << 8;
		}
	}
	return val;
}
module.exports = {
	ab2hex,
	getAge,
	crc16_false,
	Data_Decrypt,
	convertFloat,
	Current_date,
	date_format,
	HideTel,
	isNull,
	getImgSrc,
	Dayz,
	Turn_Date,
	throttle,
	debounce,
	toast,
	random,
	requestOpenBluetooth,
	toDouble,
	hexToString,
	getCurrentMonthTime,
	BytesToIntBigEndian,
	compareVersion,
	getDateYYYYMMddHHMMSS
}